import Vue from 'vue'
import VueRouter from 'vue-router'
const routerPush = VueRouter.prototype.push;

VueRouter.prototype.push = function (location) {
  return routerPush.call(this, location).catch(err => {})
};
Vue.use(VueRouter)
const routes = [
  {
    path: '/',
    redirect:"/home"
  },
  {
    path: '/home',
    name: 'home',
    meta:{
      num:0,
      isTar:true
    },
    component: () => import(/* webpackChunkName: "home" */ '../views/home.vue'),
    children:[
      {
        path:"/home/popup",
        name:"popup",
        component:()=>import(/* webpackChunkName:"popup" */"../views/searchPopup.vue")
      }
    ]
  },
  {
    path:"/topic",
    name:"topic",
    meta:{
      num:1,
      isTar:true
    },
    component:()=>import(/* webpackChunkName:"topic" */"../views/topic.vue")
  },
  {
    path:"/type",
    name:"type",
    meta:{
      num:2,
      isTar:true
    },
    component:()=>import(/* webpackChunkName:"type" */"../views/type.vue")
  },
  {
    path:"/cart",
    name:"cart",
    meta:{
      num:3,
      isTar:true
    },
    component:()=>import(/* webpackChunkName:"cart" */"../views/cart.vue")
  },
  {
    path:"/me",
    name:"me",
    meta:{
      num:4,
      isTar:true
    },
    component:()=>import(/* webpackChunkName:"me" */"../views/me.vue")
  }
]

/*
  路由守卫:
    正常通过路由规则加载不同的组件,不同的路由规则之间还可以进行跳转
    例如: 
      如果从首页跳转 到 专题页 (/home => /topic)
      如果从其他跳转 到 购物车页 (/home => /topic)
        此时你在访问的是购物车,购物车在不登录的时候,不能显示
        如何判断是否登录,根据token
    语法格式:
      router.beforeEach((to,from,next)=>{
        参数1:你要去哪个路由
        参数2:你从哪里来
        参数3:方法,下一步
      })
*/
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
router.beforeEach((to,from,next)=>{
  // console.log('to:',to);
  // console.log('from:',from);
  // console.log('next:',next);
  // 需求,没有token 就不让你访问购物车  /cart路由
  // 声明一个token
  if(to.path == "/cart"){
      // 进入这个分支,表示你要访问购物车,只有访问购物车,才需要判断是否有token
      let token = false; // 表示有token
      if(token){
        next();
      }else{
        next("/me")
      }
  }else{
      next();
  }
  
})

// 定义路由守卫
export default router

